package com.qiantu.phone.widget;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;

import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;

/**
 * Created by luzx on 2019/05/16.
 */
public class CursorFrameTextView extends AppCompatEditText {

    private Drawable mCursorDrawable;
    private Bitmap mCursorBitmap;
    private boolean show = true;
    private Paint mPaint;
    private RectF mRectF;
    private RectF backgroundRectF;
    private Handler mHandler;
    private float radius;
    private float strokeWidth;
    private boolean selected;
    private int selectedColor;
    private int unSelectedColor;
    private int backgroundColor;
    private OnPasteCallback mOnPasteCallback;
    private ClipboardManager mClipboardManager;

    public CursorFrameTextView(Context context) {
        this(context, null);
    }

    public CursorFrameTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CursorFrameTextView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mCursorDrawable = getResources().getDrawable(R.drawable.edit_text_cursor_2_18, context.getTheme());
        if (mCursorDrawable != null) {
            mCursorBitmap = drawableToBitmap(mCursorDrawable);
        }
        radius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
        strokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics());
        selectedColor = AppApplication.getInstance().getThemeColor(R.attr.themeColor);
        unSelectedColor = 0x00000000;
        backgroundColor = AppApplication.getInstance().getThemeColor(R.attr.secondaryColor9);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(selectedColor);
        mPaint.setStrokeWidth(strokeWidth);
        mRectF = new RectF();
        mHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 1) {
                    invalidate();
                }
            }
        };
        backgroundRectF = new RectF();
        setBackgroundColor(AppApplication.getInstance().getThemeColor(R.attr.shapeSolidColor));
        setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
//                showPopWindow();
                return false;
            }
        });
        setFocusable(false);
        setFocusableInTouchMode(false);
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 获取 drawable 长宽
        int width = drawable.getIntrinsicWidth();
        int heigh = drawable.getIntrinsicHeight();

        drawable.setBounds(0, 0, width, heigh);

        // 获取drawable的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 创建bitmap
        Bitmap bitmap = Bitmap.createBitmap(width, heigh, config);
        // 创建bitmap画布
        Canvas canvas = new Canvas(bitmap);
        // 将drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        backgroundRectF.left = radius / 2;
        backgroundRectF.top = radius / 2;
        backgroundRectF.right = getMeasuredWidth() - radius / 2;
        backgroundRectF.bottom = getMeasuredHeight() - radius / 2;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPaint.setColor(backgroundColor);
        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawRoundRect(backgroundRectF, radius, radius, mPaint);
        mPaint.setStyle(Paint.Style.STROKE);
        if (selected) {
            if (mCursorDrawable != null && (getText() == null || getText().length() == 0)) {
                if (show) {
                    mRectF.top = (getHeight() - mCursorBitmap.getHeight()) / 2;
                    mRectF.left = (getWidth() - mCursorBitmap.getWidth()) / 2;
                    mRectF.right = mRectF.left + mCursorBitmap.getWidth();
                    mRectF.bottom = mRectF.top + mCursorBitmap.getHeight();
                    mPaint.setShadowLayer(0, 0, 0, selectedColor);
                    canvas.drawBitmap(mCursorBitmap, mCursorDrawable.copyBounds(), mRectF, mPaint);
                    show = false;
                } else {
                    mRectF.setEmpty();
                    canvas.drawBitmap(mCursorBitmap, mCursorDrawable.copyBounds(), mRectF, mPaint);
                    show = true;
                }
                mHandler.removeCallbacksAndMessages(null);
                mHandler.sendEmptyMessageDelayed(1, 600);
            } else {
                super.onDraw(canvas);
            }
            mPaint.setStrokeWidth(strokeWidth / 2);
            mPaint.setColor(selectedColor);
            canvas.drawRoundRect(backgroundRectF, radius, radius, mPaint);
        } else {
            mPaint.setColor(unSelectedColor);
            mPaint.setStrokeWidth(strokeWidth / 2);
            canvas.drawRoundRect(backgroundRectF, radius, radius, mPaint);
            super.onDraw(canvas);
        }
    }

    @Override
    public void setSelected(boolean selected) {
        this.selected = selected;
        show = true;
        invalidate();
    }

    @Override
    protected void onCreateContextMenu(ContextMenu menu) {
        super.onCreateContextMenu(menu);
    }

//    @Override
//    protected boolean getDefaultEditable() {
//        return false;
//    }


    @Override
    public boolean onTextContextMenuItem(int id) {
        switch (id) {
            case android.R.id.cut:
                break;
            case android.R.id.paste:
                if(mOnPasteCallback != null){
                    if(mClipboardManager == null){
                        mClipboardManager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                    }
                    ClipData data = mClipboardManager.getPrimaryClip();
                    if (data != null && data.getItemCount() > 0) {
                        ClipData.Item item = data.getItemAt(0);
                        if (item != null) {
                            //item.getText()部分手机可能会在剪切板没有相关的文本内容返回null.
                            CharSequence charSequence = item.getText();
                            setText(null);
                            if (charSequence != null && TextUtils.isDigitsOnly(charSequence)) {
                                //获取粘贴信息
                                mOnPasteCallback.onPaste(charSequence.toString());
                            }
                            return true;
                        }
                    }
                }
                break;
            case android.R.id.copy:
                break;
        }
        return super.onTextContextMenuItem(id);
    }

    public interface OnPasteCallback {
        void onPaste(String data);
    }

    public void setOnPasteCallback(OnPasteCallback onPasteCallback) {
        mOnPasteCallback = onPasteCallback;
    }
}
